const util = require("../../utils/util")
const app = getApp()
Page({
  data: {
    api: app.globalData.api,
    login_uid: "",
    item: {}, // category cid(类别id) ctime ftime hot id(商品id) logo price product uid(商家id) user
    comments : [],
    collect_status: 2,
    follow_status: 2,
    isDisabled: false,
    text: "",
  },
  //{{cid==item.id?'category active':'category'}}
  addToCart(e){ //添加到购物车
    console.log(this.data.item.uid)
    util.http('/cart/add?count=1&pid='+this.data.item.id+'&uid='+this.data.login_uid, resp=>{
      util.alert("添加购物车成功！")
      this.setData(this.data)  //将变化的数据更新
    })
  },
  readyToBuy(){
    wx.setStorageSync('商品单价', this.data.item.price)

    util.redirect("createorder")
  },
  changeFollow(){
    
    if(this.data.follow_status == 1){
      
      util.http('/follow/cancel?uid='+this.data.login_uid+'&sid='+this.data.item.uid, resp=>{
        console.log(resp)
        this.data.follow_status = 2
        this.setData(this.data)  //将变化的数据更新
      })
    }else{
      util.http('/follow/add?uid='+this.data.login_uid+'&sid='+this.data.item.uid, resp=>{
        this.data.follow_status = 1
        console.log(resp)
        this.setData(this.data)  //将变化的数据更新
      })
    }
    
  },
  changeCollect(){
    var that = this
    if(this.data.collect_status == 1){
      util.http('/cancelcollect?pid='+this.data.item.id+'&uid='+this.data.login_uid, resp=>{
        util.alert(resp);
        that.data.collect_status = 2;
        this.setData(this.data)  //将变化的数据更新
      })
    }else{
      util.http('/addcollect?pid='+this.data.item.id+'&uid='+this.data.login_uid, resp=>{
        util.alert(resp);
        that.data.collect_status = 1;
        this.setData(this.data)  //将变化的数据更新
      })
    }
  },
  onShow(){
    this.onLoad()
  },
  onLoad(options) {
    this.data.item = wx.getStorageSync('商品信息')
    console.log("商品名称")
    console.log(this.data.item)
    this.data.login_uid = wx.getStorageSync('uid')
    this.setData(this.data)
    util.http('/comment/list?pid=' + this.data.item.id, resp=>{
      this.data.comments = resp;
      this.setData(this.data)
    })
    util.http('/ifcollected?pid='+this.data.item.id+'&uid='+this.data.login_uid, resp=>{
      console.log(resp)
      this.data.collect_status = 1
      this.setData(this.data)
    })
    util.http('/follow/iffollowed?uid='+this.data.login_uid+'&sid='+this.data.item.uid, resp=>{
      console.log("是否关注")
      console.log(resp)
      this.data.follow_status = resp
      this.setData(this.data)  //将变化的数据更新
    })

    if (this.data.item.num === 0) {   //当disabled=false时
      this.setData({  
        isDisabled: true,  //修改isDisabled的值为true（即启用状态）
        text: "正在补货"    //文字修改为“编辑”
      })
    }
    else {    //当disabled=true时
      this.setData({  
        isDisabled: false,    //修改isDisabled的值为false（即禁用状态）
        text: "购买"   //文字修改为“保存”
      })
    }


    //当全局变量中的数据有更改，需要更新到页面
    this.setData(this.data)
  },
})